package org.ht.viewer;

import java.awt.Component;
import java.awt.Container;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.ButtonGroup;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.JToggleButton.ToggleButtonModel;

public class ItemListenerEntity implements ItemListener {
	public ItemListenerEntity(Container container) {
		super();
		this.container = container;
	}

	Container container;

	@Override
	public void itemStateChanged(ItemEvent e) {
		JRadioButton jop = (JRadioButton) e.getSource();
		// TODO 两种做法隐藏或者disable
		// if (!jop.isSelected()) {
		// container.setVisible(false);
		// } else {
		// container.setVisible(true);
		// }
		if (!jop.isSelected()) {
			disable(container);
		} else {
			enable(container);
		}
	}

	private void disable(Container target) {
		for (Component c : target.getComponents()) {
			if (c instanceof JToggleButton) {
				JToggleButton obj = (JToggleButton) c;
				if (obj.getModel() instanceof ToggleButtonModel) {
					ButtonGroup group = ((ToggleButtonModel) obj.getModel())
							.getGroup();
					if (group != null) {
						group.clearSelection();
					}
				}
				obj.setSelected(false);
				obj.setEnabled(false);

			} else if (c instanceof JTextField) {
				JTextField obj = (JTextField) c;
				obj.setText("");
				obj.setEnabled(false);
			} else if (c instanceof Container) {
				Container obj = (Container) c;
				disable(obj);
			}
		}
	}

	private void enable(Container target) {
		for (Component c : target.getComponents()) {
			if (c instanceof JToggleButton) {
				JToggleButton obj = (JToggleButton) c;
				obj.setEnabled(true);
			} else if (c instanceof JTextField) {
				JTextField obj = (JTextField) c;
				obj.setEnabled(true);
			} else if (c instanceof Container) {
				Container obj = (Container) c;
				enable(obj);
			}
		}
	}
}
